package com.zhijian.warehouse.manage.aop;

import com.zhijian.warehouse.manage.config.Constants;
import com.zhijian.warehouse.manage.util.AnnotationValidationUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Objects;

@Aspect
@Component
public class ValidateAop {

    @Pointcut("@annotation(com.zhijian.response.annotation.Response)")
    public void toValidPointCut() {
        // Do nothing because of pointcut
    }

    @Before("toValidPointCut()")
    public void before(JoinPoint joinPoint) {
        //获取request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String language = request.getHeader("Language");
        if (StringUtils.isBlank(language)) {
            //默认中文
            language = Constants.ZH_CN;
        }
        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            String finalLanguage = language;
            Arrays.stream(args).forEach(a -> {
                if (!Objects.isNull(a)) {
                    AnnotationValidationUtils.validate(finalLanguage, a);
                }
            });
        }
    }
}
